package net.oschina.dajiangnan.wx.process.pay.tools;

import java.util.HashMap;

import net.oschina.dajiangnan.wx.util.HttpTookit;
import net.oschina.dajiangnan.wx.util.RandomUtil;
import net.oschina.dajiangnan.wx.util.Signature;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import net.oschina.dajiangnan.wx.constants.Config;
import net.oschina.dajiangnan.wx.constants.DynamicValue;
import net.oschina.dajiangnan.wx.process.pay.bean.LoadBillResult;
import net.oschina.dajiangnan.wx.process.pay.bean.URLShortReult;
import net.oschina.dajiangnan.wx.process.pay.xmlbean.LoadBillReq;

public class Other {

	// 生成短连接URL
	private static final String INIT_SHORT_URL_url = "https://api.weixin.qq.com/cgi-bin/shorturl?access_token=";

	// 下载对账单URL
	private static final String DOWN_LOAD_BILL_URL = "https://api.mch.weixin.qq.com/pay/downloadbill";

	private static Logger logger = Logger.getLogger(Other.class);

	/**
	 * 短连接转换
	 * http://mp.weixin.qq.com/wiki/10/165c9b15eddcfbd8699ac12b0bd89ae6.html
	 * @param longURL
	 * @return URLShortReult
	 */
	public static URLShortReult initShortURL(String longURL) {
		HashMap<String, String> map = new HashMap<String, String>(2);
		map.put("action", "long2short");
		map.put("long_url", longURL);
		String respStr = new HttpTookit().doPost(INIT_SHORT_URL_url
				+ DynamicValue.getAccessToken(), JSON.toJSONString(map),null,null,"UTF-8");
		logger.info("respJSONStr of getting short url:" + respStr);
		return JSON.parseObject(respStr, URLShortReult.class);
	}

	/**
	 * 下载对账单
	 * https://pay.weixin.qq.com/wiki/doc/api/micropay.php?chapter=9_6
	 * @param bill_date
	 *            格式yyyymmdd
	 * @param bill_type
	 *            ALL，返回当日所有订单信息，默认值;SUCCESS，返回当日成功支付的订单;REFUND，返回当日退款订单;REVOKED
	 *            ，已撤销的订单;
	 */
	public static LoadBillResult downloadbill(String bill_date, String bill_type) {

		logger.info("DownLoadBill,request params:bill_date" + bill_date
				+ ",bill_type:" + bill_type);
		LoadBillReq xml_req = new LoadBillReq();
		xml_req.setBill_date(bill_date);
		xml_req.setBill_type(bill_type);
		xml_req.setAppid(Config.appid);
		xml_req.setMch_id(Config.mch_id);
		xml_req.setNonce_str(RandomUtil.getRandomStr(32));
		try {
			xml_req.setSign(Signature.getSign(xml_req, null, Config.apikey));
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		logger.debug("DownLoadBill Request XML:\r\n" + xml_req.toString());
		String resp_datas = new HttpTookit().doPost(DOWN_LOAD_BILL_URL,
				xml_req.toString(),null,null,"UTF-8");
		logger.debug("DownLoadBill Response Datas:\r\n" + resp_datas);

		LoadBillResult result = new LoadBillResult();
		result.setAppid(Config.appid);
		result.setMch_id(Config.mch_id);
		result.setBill_date(bill_date);
		result.setBill_type(bill_type);
		result.setBill_data(resp_datas);
		logger.info(result.toString());
		return result;
	}

}
